package com.summer.campussct.schedule;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

@Component
@Slf4j
public class TempFileSchedule {

    @Value("${file-position.rootPath}")
    private String rootPath;
    @Value("${file-position.tempPath}")
    private String tempPath;

    // 每天0点0分0秒清理临时文件
    @Scheduled(cron = "0 0 0 * * ?")
    public void clearTempFiles(){
        log.info("正在清理临时文件，目录：{}", rootPath + tempPath);
        try(Stream<Path> list = Files.list(Paths.get(rootPath + tempPath))) {
            list.forEach(e -> {
                if (Files.isDirectory(e)){
                    return;
                }
                try {
                    Files.delete(e);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
